<?php
/**
 * Created by PhpStorm.
 * User: geo
 * Date: 16/6/20
 * Time: 下午2:31
 */

// 开启xdebug调试
setcookie('XDEBUG_SESSION', 'phpstorm', 0, '/');

// 设置市区
date_default_timezone_set('Asia/Shanghai');


$GLOBALS['json_post'] = json_decode(file_get_contents('php://input'));

// 错误码
$GLOBALS['err_codes'] = [
// ERR000-ERR099 系统问题
    'sys-fatal' => 0,           // 系统严重错误,客户端需重启
    'action-miss' => 1,        // 非法操作:无动作字段
    'action-nologin' => 2,         // 非法操作:未登录或登陆超时,请重新登陆
    'action-unknown' => 3,    // 非法操作:无法识别动作

// ERR100-ERR149 账号问题
    'login-fail' => 100,        // 登陆失败:用户名或密码或验证码有误
    'reg-used' => 101,          // 注册失败:账户名不可用
    'reg-format' => 102,        // 注册失败:账号名不合法
// ERR150-ERR199 数据库问题
    'db-err' => 150,            // 数据库错误
    // ERR200-ERR249 游戏问题
    'gm-unknown' => 200          // 无法识别游戏
];

// 工具函数
function err_reply($err, $errtype=null) {
    $json = json_encode($errtype==null?['err'=>$err]:['err'=>$err, 'errtype'=>$errtype]);
    exit($json);
}


$action = strrchr($_SERVER['PHP_SELF'], '/');
// 是否有action
if ($action === FALSE || strlen($action) < 1)
    err_reply($GLOBALS['err_codes']['action-miss']);

// 获取action
$action = substr($action, 1);

// 启动session
session_start();

// 二维码生成工具
function _gen_bookcode($bkid, $code) {
    include_once '3rd/php/phpqrcode/qrlib.php';
    $filename = 'gen/bkcode/' . $bkid . '.png';
    QRcode::png($code, $filename, 'H', 4);
}
//[ 用于开发简化，显示代码提示
//$db = new mysqli();
//$db->close();
//]

require_once 'lib/geo/db_utils.php';

function gb_db_err($db, $err){
    //TODO 不做处理交由具体环境处理
    err_reply($GLOBALS['err_codes']['db-err']);
}
$GLOBALS['DB_ERR_CB'] = 'gb_db_err';

//======================Services=======================//
/**
 * 用户登录
 * @param $db
 * @param $data
 */
function login($db, $data) {

    $res = db_select($db, 't_user', '*', [
        'name' => $data->name,
        'pswd' => $data->pswd
    ]);
    if ($res) {
        if ($row = $res->fetch_object()) {
            // 登录成功,准备返回信息
            $user = [
                'id' => $row->id,
                'name' => $row->name,
                'signin ' => $row->signin
            ];
            // 更新登录时间
            db_update($db, 't_user', ['signin' => time()], ['id' => $row->id]);
            // 返回
            echo json_encode($user);
            // session中记录信息
            $user['id'] = $row->id; // 加入用户ID
            $user['pswd'] = $row->pswd; // 缓存用户密码
            $_SESSION['user'] = $user;
            return;
        } else {
            // 登录失败
            err_reply($GLOBALS['err_codes']['login-fail']);
        }
    } else {
        err_reply($GLOBALS['err_codes']['db-err']);
    }
}

/**
 * 用户注册
 * @param $db
 * @param $data
 */
function register($db, $data) {
    $time = time();
    $dataToInsert = [
        //'user_id' => $uid,
        'name' => $data->name,
        'pswd' => $data->pswd,
        'signup' => $time,
        'signin' => $time
    ];
    $res = db_insert($db, 't_user', $dataToInsert);
    if ($res) {
        echo '{}';
        return;
    } else {
        //err_reply($db->error);
        err_reply($GLOBALS['err_codes']['reg-used']);
    }
}

/**
 * 用户注销
 * @param $db
 * @param $data
 */
function logout($db, $data) {
    session_unset();
    session_destroy();
    echo '{}';
}

/**
 * 添加新事件
 * @param $db
 * @param $data
 */
function add_note($db, $data) {
    $time = time();
    $dataToInsert = [
        //'user_id' => $uid,
        'owner' => $_SESSION['user']['id'],
        'created' => $time,
        'modified' => $time
    ];
    $res = db_insert($db, 't_note', $dataToInsert);
    if ($res) {
        echo json_encode(['id' => db_last_insert_id($db, 't_note')]);
        return;
    } else {
        //err_reply($db->error);
        err_reply($GLOBALS['err_codes']['db-err']);
    }
}

function update_note($db, $data) {
    $time = time();
    $dataToUpdate = [
        'title' => $data->title,
        'detail' => $data->detail,
        'modified' => $time
    ];

    $res = db_update($db, 't_note', $dataToUpdate, ['id' => $data->id]);

    if ($res) {
        echo '{}';
        return;
    } else {
        err_reply($GLOBALS['err_codes']['db-err']);
    }
}

/**
 * 列表用户的事件记录
 * @param $db
 * @param $data
 */
function list_note($db, $data) {

    $dataToSel = [
        'id' => 'id',
        'title' => 'title',
        'detail' => 'detail',
        'created' => 'created',
        'modified' => 'modified'
    ];

    $where = ['owner' => $_SESSION['user']['id']];

    $res = db_select($db, 't_note', $dataToSel, $where);
    if ($res) {
        echo json_encode($res->fetch_all(MYSQLI_ASSOC));
        return;
    } else {
        //err_reply($db->error);
        err_reply($GLOBALS['err_codes']['db-err']);
    }
}

/**
 * 删除事件
 * @param $db
 * @param $data
 */
function delete_note($db, $data) {
    if (db_delete($db, 't_note', ['id' => $data->id]))
        echo '{}';
    else
        err_reply($GLOBALS['err_codes']['db-err']);
}

/**
 * 获取一个事件记录
 * @param $db
 * @param $data
 */
function get_note($db, $data) {
    $res = db_select($db, 't_note', null, [id => $data->id]);
    if ($res && $row = $res->fetch_assoc()) {
        echo json_encode($row);
    } else {
        err_reply($GLOBALS['err_codes']['db-err']);
    }
}
// 定义命令代码
$cmd_code = [
    'login'         => 'lg',
    'register'      => 'rg',
    'logout'        => 'lo',
    'add_note'      => 'an',
    'update_note'   => 'un',
    'list_note'     => 'ln',
    'delete_note'   => 'dn',
    'get_note'      => 'gn'
 ];

// 注册服务
$sv[$cmd_code['register']] = 'register';
$sv[$cmd_code['login']] = 'login';
$sv[$cmd_code['logout']] = 'logout';
$sv[$cmd_code['add_note']] = 'add_note';
$sv[$cmd_code['update_note']] = 'update_note';
$sv[$cmd_code['list_note']] = 'list_note';
$sv[$cmd_code['delete_note']] = 'delete_note';
$sv[$cmd_code['get_note']] = 'get_note';

// 监测action是否存在
// TODO 考虑将此处理向前移动
$do_action = $sv[$action];

if (function_exists($do_action)) {
// 执行服务
    $GLOBALS['db_name'] = 'flynote';
    $db = db_open('localhost', 'flynote', '111111', $GLOBALS['db_name']);
// 转换字符串
    $json_post = db_escape_string($db, $json_post);
// 执行
    $do_action($db, $json_post);
//
    db_close($db);
} else {
    err_reply($GLOBALS['err_codes']['action-unknown']);
}